/*
 * @Author: wangdazhuang
 * @Date: 2024-10-19 09:53:01
 * @LastEditTime: 2025-02-18 14:18:20
 * @LastEditors: wangdazhuang
 * @Description: 
 * @FilePath: /pornhub_app/lib/http/http_resp_convert.dart
 */
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:pornhub_app/http/base_repsponse_model.dart';
import 'package:pornhub_app/env/environment_service.dart';
import '../utils/logger.dart';
import 'http_service.dart';

///响应处理
abstract class HttpRespConvert<T> {
  static convertRsp<T>(
    Response resp,
    JSON2ModelComplete<T>? complete,
    bool? requestEntireModel, {
    required String method,
    required String url,
    Map<String, dynamic>? body,
    Map<String, dynamic>? queryMap,
  }) async {
    BaseRespModel result = resp.data;
    final json = result.data;
    final jsonStr = const JsonEncoder.withIndent('  ').convert(result.toJson());
    final logStr = jsonStr.replaceAll(RegExp(r'[^\x00-\x7F]'), '');
    logger.d(
        "${Environment.kbaseAPI}$url>>$method>>${method == "GET" ? queryMap : body}>>response data:>>> \n$logStr");
    if (result.code != 200 || json == null) {
      return null;
    }
    if (complete == null) {
      return json;
    }
    //直接返回数组的情况
    if (json is List) {
      List arr = json;
      final models = await compute(_json2Model<T>, [arr, complete]);
      return models;
    }
    //空json的情况
    if (Map.from(json).isEmpty) {
      return null;
    }
// {code:200,msg:success,data: {
// data:[...]}
// }
    bool hasarr = (json).containsKey("data") && json["data"] is List;

// {code:200,msg:success,data: {
// data:{....}}
// }

    bool hasdataJson = (json).containsKey("data") && json["data"] is Map;
    if (hasdataJson) {
      final v = Map<String, dynamic>.from(json["data"]);
      return await compute(_json2Model<T>, [v, complete]);
    }
    if (hasarr && (requestEntireModel == null || requestEntireModel == false)) {
      List arr = json["data"];
      return await compute(_json2Model<T>, [arr, complete]);
    }
    return await compute(_json2Model<T>, [json, complete]);
  }

  ///json2model
  static Future _json2Model<T>(List<dynamic> parameters) async {
    assert(parameters.isNotEmpty && parameters.length == 2,
        'paramters must not null and length is 2!');
    final source = parameters[0];
    JSON2ModelComplete<T> complete = parameters[1];
    if (source is List) {
      final models = source.map((e) => complete(e)).toList();
      return models;
    }
    final model = complete(Map<String, dynamic>.from(source));
    return model;
  }
}
